package com.lunasoft.server;

import com.lunasoft.protobuf.TESMsg;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author Jierry
 * @version 2016/7/14.
 */
public class ServerHandler extends SimpleChannelInboundHandler<TESMsg.Message> {

    private static Logger logger = LoggerFactory.getLogger(ServerHandler.class);

    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TESMsg.Message message) throws Exception {
        System.out.println("proxy said:" + message);
        int header = message.getHeader();
        while (true){
            TESMsg.BasicMsg.Builder b = TESMsg.BasicMsg.newBuilder();
            b.setTesId(message.getLoginInfo().getUserId());
            b.setTime(System.currentTimeMillis());
            channelHandlerContext.writeAndFlush(b.build());

            TimeUnit.SECONDS.sleep(2);
            TESMsg.BasicMsg.Builder b2 = TESMsg.BasicMsg.newBuilder();
            b2.setTesId(message.getLoginInfo().getUserId());
            b2.setTime(2);
            channelHandlerContext.writeAndFlush(b2.build());

            TimeUnit.SECONDS.sleep(1);
        }
//        switch (header){
//            case 101:
//                while (true){
//                    TESMsg.BasicMsg.Builder b = TESMsg.BasicMsg.newBuilder();
//                    b.setTesId(message.getLoginInfo().getUserId());
//                    b.setTime(1000);
//                    channelHandlerContext.writeAndFlush(b.build());
//                    TimeUnit.SECONDS.sleep(1);
//                }
//                break;
//            default:
//                break;
//        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        logger.info("pushClient:" + incoming.remoteAddress() + "在线");

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        logger.info("Client:" + incoming.remoteAddress() + "掉线");
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        logger.info(cause.getMessage());
        ctx.close();
    }
}
